<template>
  <div class="table-box">
    <ProTable
        ref="proTable"
        title="文章列表"
        :columns="columns"
        :pagination="true"
        :request-api="getTableList"
        :init-param="initParam"
        :data-callback="dataCallback"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button v-auth="'/article/add'" type="primary" :icon="CirclePlus" @click="openDrawer('新增', { cate_id: '' })">
          新增文章
        </el-button>
        <el-button
            v-auth="'/article/delete/*'"
            type="danger"
            :icon="Delete"
            plain
            :disabled="!scope.isSelected"
            @click="batchDelete(scope.selectedListIds)"
        >
          批量删除
        </el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- pics -->
      <template #pics="scope">
        <el-image :src="scope.row.pics" style="height: 65px;" :preview-src-list="getPicList(scope.row.pics)" preview-teleported fit="cover" />
      </template>
      <!-- status -->
      <template #status="scope">
        <el-switch
            :model-value="scope.row.status"
            active-text="启用"
            inactive-text="禁用"
            inline-prompt
            :active-value="1"
            :inactive-value="0"
            :disabled="!authButton('/article/change_status/*')"
            @click="changeStatus(scope.row)"
        />
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" v-auth="'/article/edit/*'" @click="openDrawer('编辑', scope.row)"
        >编辑</el-button
        >
        <el-button type="danger" link :icon="Delete" v-auth="'/article/delete/*'" @click="delArticle(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <ArticleDrawer ref="drawerRef" />
  </div>
</template>

<script lang="ts">
export default {
  name: "articleManage",
}
</script>

<script setup lang="ts">
import { CirclePlus, Delete, EditPen, View } from "@element-plus/icons-vue";
import ArticleDrawer from "@/views/app/article/ArticleDrawer.vue";
import ProTable from "@/components/ProTable/index.vue";
import {computed, onMounted, reactive, ref} from "vue";
import { article } from "./article";
import {
  addArticleApi,
  changeStatusApi,
  articlePageListApi,
  deleteArticleByIdApi,
  deleteArticleApi,
  editArticleApi,
} from "@/api/modules/article";
import { ProTableInstance } from "@/components/ProTable/interface";
import { cateTreeCacheApi } from "@/api/modules/cate.ts";
import { useHandleData } from "@/hooks/useHandleData.ts";
import { authButton } from "@/hooks/useAuthButton.ts";
import { Recordable } from "@/interface/types.ts";
import { globalStore } from "@/stores/modules/global.ts";
import { dictValuesByDictCodeApi } from "@/api/modules/dict.ts";

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});
const cateTree = ref<any[]>([]);
const articleOrigins = ref<any[]>([]);
const articleFeatures = ref<any[]>([]);
const { columns } = article(cateTree.value, articleFeatures.value, articleOrigins.value);

// 获取文章
onMounted( () => {
  cateTreeCacheApi().then(res => {
    cateTree.value = res.data as any[];
    proTable.value?.updateSearchColumn({ key: "cate_id", data: res.data });
  });
  dictValuesByDictCodeApi("origins").then(res => {
    articleOrigins.value = res.data as any[];
    proTable.value?.updateSearchColumn({ key: "origin", data: res.data });
  })
  dictValuesByDictCodeApi("features").then(res => {
    articleFeatures.value = res.data as any[];
    proTable.value?.updateSearchColumn({ key: "feature", data: res.data });
  })
});

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.create_time && (newParams.startTime = newParams.create_time[0]);
  newParams.create_time && (newParams.endTime = newParams.create_time[1]);
  delete newParams.create_time;
  return articlePageListApi(newParams);
};

const getPicList = (pics: string) => {
  return pics.split(";");
}

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    rows: data.rows,
    total: data.total,
    page_num: data.page_num,
    page_size: data.page_size
  };
};

const globalState = globalStore();
const theme = computed(() => globalState.isDark ? "dark" : "classic");
const language = computed(() => globalState.language == "zh" ? "zh_CN" : "en_US");

// 打开 dialog(新增、查看、编辑)
const drawerRef = ref();
const openDrawer = (title: string, rowData: Partial<Recordable> = {}) => {
  console.log(rowData);
  let params = {
    title,
    rowData: { ...rowData },
    isView: title === "查看",
    cateTree: cateTree.value,
    articleOrigins: articleOrigins.value,
    articleFeatures: articleFeatures.value,
    theme: theme.value,
    language: language.value,
    api: title === "新增" ? addArticleApi : title === "编辑" ? editArticleApi : "",
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value.acceptParams(params);
};

// 删除文章信息
const delArticle = async (row: Recordable) => {
  await useHandleData(deleteArticleByIdApi, row.id, `删除【${row.title}】文章`);
  proTable.value?.getTableList();
};

// 批量删除文章信息
const batchDelete = async (pds: string[]) => {
  await useHandleData(deleteArticleApi, { pds }, "删除所选文章信息");
  proTable.value?.clearSelection();
  proTable.value?.getTableList();
};

// 切换状态
const changeStatus = async (row: Recordable) => {
  if (!authButton("/article/change_status/*")) {
    return;
  }
  await useHandleData(changeStatusApi, row.id, `切换【${row.title}】文章状态`);
  proTable.value?.getTableList();
};
</script>

<style scoped lang="scss"></style>
